
var app = getApp()
var Bmob = require('../../utils/bmob.js');
var common = require('../../utils/common.js');
Page({
  data: {
    orderData: {},
    orderInfo: {},
    orderStatus: { '0': '待付款', '1': '待发货', '2': '待收货', '3': '待评价', '4': '退款审核中', '5': '退款中', '6': '已完成', '7': '已关闭' },
    selectAddressId: '',
    goodsAdditionalInfo: {},
    hasAdditionalInfo: false,
    customFields: [],
    orderId: '',
    isFromTemplateMsg: false,
    originalPrice: '',
    useBalance: '',
    freightAdress: {},
    express_fee: '',
    discount_cut_price: 0
  },
  onLoad: function (options) {
    this.setData({
      orderId: options.detail,
      isFromTemplateMsg: options.from === 'template_msg' ? true : false,
      franchiseeId: options.franchisee || ''
    })
    this.dataInitial();
  },
  // 每个页面数据初始化函数 dataInitial
  dataInitial: function () {
    this.getOrderDetail(this.data.orderId);
    //this.initialAddressId();
  },
  getOrderDetail: function (orderId) {
    var that = this;
    var OrderList = Bmob.Object.extend("orderList");
    var order = new Bmob.Query(OrderList);
    var currentUser = Bmob.User.current();
    var objectId = currentUser.id;
    var isme = new Bmob.User();
    isme.id = objectId;     //当前用户的objectId
    order.equalTo("users", isme);
    //order.include("goodsInfo");
    order.include("sub_shop_info");
    ///  shoppingCart.equalTo("shopping_car_id", "bmob");
    order.get(orderId, {
      success: function (res) {
        console.log(res);
        var orderInfo = {};
        orderInfo = res.attributes;
        orderInfo.order_id = res.id;
        orderInfo.createdAt = res.createdAt;
        that.setData({

          orderInfo: orderInfo,
          // hasAdditionalInfo: hasAdditionalInfo,
          // discount_cut_price: form_data.discount_cut_price,
          // useBalance: Number(form_data['use_balance']),
          // express_fee: res.data[0]['express_fee']
        });
        // app.setPreviewGoodsInfo(additional_info_goods);

        /*
         if (form_data.is_self_delivery == 1) {
           // 自提
           that.getFreigtAdress();
         } else {
           // 快递
           address_id = form_data.address_info.address_id;
           that.setData({
             selectAddressId: address_id,
           })
         }
 
         app.setGoodsAdditionalInfo(form_data.additional_info || {});*/
      }
    })

  },
  getOrderDetail1: function (orderId) {
    var that = this;
    app.getOrderDetail({
      data: {
        order_id: orderId,
        sub_shop_app_id: this.data.franchiseeId
      },
      success: function (res) {
        var data = res.data[0],
          form_data = data.form_data,
          hasAdditionalInfo = false,
          additional_info_goods = [],
          additional_goodsid_arr = [],
          address_id = '';

        for (var i = 0; i < form_data.goods_info.length; i++) {
          var deliveryId = form_data.goods_info[i].delivery_id,
            goodsId = form_data.goods_info[i].id;

          if (deliveryId && deliveryId != '0' && additional_goodsid_arr.indexOf(goodsId) == -1) {
            additional_info_goods.push(form_data.goods_info[i]);
            additional_goodsid_arr.push(goodsId);
            hasAdditionalInfo = true;
          }
        }
        that.setData({
          orderData: data,
          orderInfo: form_data,
          hasAdditionalInfo: hasAdditionalInfo,
          discount_cut_price: form_data.discount_cut_price,
          useBalance: Number(form_data['use_balance']),
          express_fee: res.data[0]['express_fee']
        });
        app.setPreviewGoodsInfo(additional_info_goods);

        if (form_data.is_self_delivery == 1) {
          // 自提
          that.getFreigtAdress();
        } else {
          // 快递
          address_id = form_data.address_info.address_id;
          that.setData({
            selectAddressId: address_id,
          })
        }

        app.setGoodsAdditionalInfo(form_data.additional_info || {});
      }
    })
  },
  orderDelete: function (e) {
    var orderId = this.data.orderId,
      that = this,
      franchiseeId = this.data.franchiseeId;
    var OrderList = Bmob.Object.extend("orderList");
    var order = new Bmob.Query(OrderList);

    app.showModal({
      content: '订单删除后不可找回，确认删除？',
      showCancel: true,
      cancelText: '取消',
      confirmText: '确定',
      confirm:function(){ 
      order.get(orderId, {
        success: function (object) {
          // The object was retrieved successfully.
          object.destroy({
            success: function (deleteObject) {
              app.turnBack()
            },
            error: function (object, error) {
              console.log('删除日记失败');
            }
          });
        },
        error: function (object, error) {
          console.log("query object fail");
        }
      })
      }

    })
  },
  cancelOrder: function (e) {
    var orderId = this.data.orderInfo.order_id,
      that = this;
      var data={};
    var Order = Bmob.Object.extend("orderList");
    var order = new Bmob.Query(Order);
    // 这个 id 是要修改条目的 id，你在生成这个存储并成功时可以获取到，请看前面的文档
 
    app.showModal({
      content: '是否取消订单？',
      showCancel: true,
      confirmText: '是',
      cancelText: '否',
      confirm: order.get(orderId, {
        success: function (result) {
          // 回调中可以取得这个 diary 对象的一个实例，然后就可以修改它了
          result.set('status', 7);

          result.save({
            success: function (res) {

              data['orderInfo.status'] = 7;
              that.setData(data);
            }


          });
          // The object was retrieved successfully.
        },
        error: function (object, error) {

        }
      })
    })
  },
  payOrder: function (e) {
    var address_info = this.data.orderInfo.address_info,
      that = this,
      order_total_price = this.data.orderInfo.order_total_price,
      order_Id;
  
    var openId = wx.getStorageSync('openid');
    var orderInfo={};
    if (!address_info && this.data.orderInfo.goods_type != 3) {
      app.showModal({
        content: '请选择邮寄地址'
      })
      return;
    }

    order_Id = this.data.orderInfo.order_id;
      
    function paySuccess(orderId, order_Id) {
      console.log(order_Id, orderId)
      var pagePath = '/pages/goodsOrderPaySuccess/goodsOrderPaySuccess?detail=' + order_Id + (that.franchisee_id ? '&franchisee=' + that.franchisee_id : '') + '&is_group=' + !!that.is_group;
      if (orderId) {
        var Order = Bmob.Object.extend("orderList");
        var order = new Bmob.Query(Order);

        order.get(order_Id, {
          success: function (result) {
            // 回调中可以取得这个 GameScore 对象的一个实例，然后就可以修改它了
           console.log(result);
            orderInfo=result.attributes;
            result.set('status', 1);
            //result.set('orderId', orderId);
            result.save();

            // The object was retrieved successfully.
          },
          error: function (object, error) {

          }
        });
      }
      app.turnToPage(pagePath, 1);

    }

    function payFail(order_Id) {
   
      if (that.is_group) {
        app.turnToPage('/pages/groupOrderDetail/groupOrderDetail?id=' + order_Id, 1);
      } else {
        app.turnToPage('/pages/goodsOrderDetail/goodsOrderDetail?detail=' + order_Id, 1);
      }
    }

    Bmob.Pay.wechatPay(order_total_price, that.data.orderInfo.goods_info[0].title + '...', '微墨生活', openId).then(function (resp) {
      console.log('resp');
      console.log(resp);
      that.setData({
        loading: true,
        dataInfo: resp
      })
      //服务端返回成功
      var timeStamp = resp.timestamp,
        nonceStr = resp.noncestr,
        packages = resp.package,
        orderId = resp.out_trade_no,//订单号，如需保存请建表保存。
        sign = resp.sign,
        order_Id = that.data.orderInfo.order_id;
      //打印订单号
    

      //发起支付
      wx.requestPayment({
        'timeStamp': timeStamp,
        'nonceStr': nonceStr,
        'package': packages,
        'signType': 'MD5',
        'paySign': sign,
        'success': function (res) {
          //付款成功,这里可以写你的业务代码
          console.log(res);
          paySuccess(orderId,order_Id);
          //app.wxPaySuccess(param);

        },
        'fail': function (res) {
          //付款失败
          console.log('付款失败');
          console.log(res);
          payFail(order_Id);
          if (res.errMsg === 'requestPayment:fail cancel') {
           // param.fail();
            return;
          }
          app.showModal({
            content: '支付失败',
            complete: param.fail
          })
          app.wxPayFail(param, res.errMsg);
        }
      })

    }, function (err) {
      payFail(order_Id);
      console.log('服务端返回失败');
      common.showTip(err.message, 'loading', {}, 6000);
      console.log(err);
    });


  },
  receiveDrawback: function () {
    var orderId = this.data.orderInfo.order_id,
      that = this;
    var OrderList = Bmob.Object.extend("OrderList");
    var order = new Bmob.Query(OrderList);
    app.showModal({
      content: '确定已收到退款？',
      showCancel: true,
      confirmText: '确定',
      cancelText: '取消',
      confirm: order.get(orderId, {
        success: function (result) {
          // 回调中可以取得这个 diary 对象的一个实例，然后就可以修改它了
          result.set('status', 7);

          result.save({
            success: function (res) {

              data['orderInfo.status'] = 7;
              that.setData(data);
            }


          });
          // The object was retrieved successfully.
        },
        error: function (object, error) {

        }
      })
    })
  },
  checkLogistics: function () {
    var orderId = this.data.orderInfo.order_id;
    app.turnToPage('/pages/logisticsPage/logisticsPage?detail=' + orderId);
  },
  sureReceipt: function () {
    var orderId = this.data.orderInfo.order_id,
      that = this;
    var OrderList = Bmob.Object.extend("orderList");
    var order = new Bmob.Query(OrderList);
    app.showModal({
      content: '确定已收到货物？',
      showCancel: true,
      confirmText: '确定',
      cancelText: '取消',
      confirm: order.get(orderId, {
        success: function (result) {
          // 回调中可以取得这个 diary 对象的一个实例，然后就可以修改它了
          result.set('status',3 );

          result.save({
            success: function (res) {
             
              that.setData({
                'orderInfo.status':3

              });
            }


          });
          // The object was retrieved successfully.
        },
        error: function (object, error) {

        }
      })
    })
  },
  makeComment: function () {
    var franchiseeId = this.data.franchiseeId,
      pagePath = '/pages/makeComment/makeComment?detail=' + this.data.orderInfo.order_id + (franchiseeId ? '&franchisee=' + franchiseeId : '');
    app.turnToPage(pagePath);
  },
  showAddressList: function () {
    var addressId = this.data.selectAddressId,
      orderId = this.data.orderInfo.order_id,
      franchiseeId = this.data.franchiseeId;

    app.turnToPage('/pages/myAddress/myAddress?id=' + addressId + '&oid=' + orderId + '&sub_shop_id=' + franchiseeId, true);
  },
  goToHomepage: function () {
    var router = app.getHomepageRouter();
    app.turnToPage('/pages/' + router + '/' + router, true);
  },
  verificationCode: function () {
    app.turnToPage('/pages/verificationCodePage/verificationCodePage?detail=' + this.data.orderInfo.order_id + '&sub_shop_app_id=' + this.data.franchiseeId);
  },
  getFreigtAdress: function () {
    var that = this;
    app.sendRequest({
      url: '/index.php?r=AppShop/getAppShopLocationInfo',
      data: {
        app_id: app.getAppId()
      },
      success: function (res) {
        that.setData({
          freightAdress: res.data
        });
      }
    });
  },
  freightGoMap: function () {
    var _this = this,
      location = _this.sub_shop_info.latitude;
    if (loation) {
      wx.openLocation({
        latitude: _this.sub_shop_info.latitude,
        longitude: _this.sub_shop_info.longitude   
        
          })
    }
     

  },
  applyDrawback: function () {
    var orderId = this.data.orderInfo.order_id,
      that = this;

    app.showModal({
      content: '确定要申请退款？',
      showCancel: true,
      confirmText: '确定',
      cancelText: '取消',
      confirm: function () {
        var OrderList = Bmob.Object.extend("orderList");
        var orderlist = new Bmob.Query(OrderList);
        orderlist.get(orderId, {
          success: function (res) {

            res.set("status", 4);
            res.save({
              success: function (res) {

               
                that.setData({
                  'orderInfo.status':4


                });
              }


            });

          },


        })

      }
    })
  },
  initialAddressId: function () {
    var that = this;
    app.sendRequest({
      url: '/index.php?r=AppShop/addressList',
      data: {
        app_id: app.getAppId()
      },
      success: function (res) {
        if (res.data.length) {
          that.setData({
            selectAddressId: res.data[0].id
          });
        }
      }
    });
  },
  freightPlayPhone: function () {
    var that = this;
    app.makePhoneCall(that.data.freightAdress.shop_contact)
  },
  seeAdditionalInfo: function () {
    app.turnToPage('/pages/goodsAdditionalInfo/goodsAdditionalInfo?from=goodsOrderDetail');
  },
  paySuccessCallback: function () {
    let orderId = this.data.orderInfo.order_id;
    let franchiseeId = this.data.franchiseeId;
    let pagePath = '/pages/goodsOrderPaySuccess/goodsOrderPaySuccess?detail=' + orderId
      + (franchiseeId ? '&franchisee=' + franchiseeId : '');
    if (!franchiseeId) {
      app.sendRequest({
        url: '/index.php?r=AppMarketing/CheckAppCollectmeStatus',
        data: {
          order_id: orderId
        },
        success: function (res) {
          if (res.valid == 0) {
            pagePath += '&collectBenefit=1';
          }
          app.turnToPage(pagePath, 1);
        }
      });
    } else {
      app.turnToPage(pagePath, 1);
    }
  }
})
